import mongoose, { ConnectOptions } from 'mongoose';

export const connectDatabase = async () => {
  const {
    MONGODB_USER,
    MONGODB_PASSWORD,
    MONGODB_HOST,
    MONGODB_PORT,
    MONGODB_DATABASE,
  } = process.env;

  if (!MONGODB_HOST || !MONGODB_PORT || !MONGODB_DATABASE) {
    throw new Error('Missing required MongoDB environment variables');
  }

  const credentials = MONGODB_USER && MONGODB_PASSWORD
    ? `${MONGODB_USER}:${MONGODB_PASSWORD}@`
    : '';

  const mongoURI = `mongodb://${credentials}${MONGODB_HOST}:${MONGODB_PORT}/${MONGODB_DATABASE}`;

  const options: ConnectOptions = {
    maxPoolSize: 10,
    serverSelectionTimeoutMS: 5000,
    socketTimeoutMS: 45000,
    family: 4,
    // 生产环境配置
    retryWrites: true,
    w: 'majority',
    readPreference: 'primary'
  };

  try {
    await mongoose.connect(mongoURI, options);
    console.log('MongoDB连接成功');
  } catch (error) {
    console.error('MongoDB连接失败:', error);
    throw error; // 重新抛出错误，由调用者决定怎么处理
  }
};


export const disconnectDatabase = async () => {
  try {
    await mongoose.disconnect();
    console.log('MongoDB连接已成功关闭');
  } catch (error) {
    console.error('关闭MongoDB连接失败:', error);
  }
};